package v1

import (
	"sweetsunnyflower/app/models/user_passenger"
	"sweetsunnyflower/app/policies"
	"sweetsunnyflower/app/requests"
	"sweetsunnyflower/pkg/auth"
	"sweetsunnyflower/pkg/response"

	"github.com/gin-gonic/gin"
)

type UserPassengersController struct {
	Controller
}

func (ctrl *UserPassengersController) Index(c *gin.Context) {

	userID := auth.CurrentIntUID(c)

	userPassengers := user_passenger.GetUserPassengers(userID)

	response.Data(c, userPassengers)
}

func (ctrl *UserPassengersController) Store(c *gin.Context) {

	request := requests.UserPassengerRequest{}
	if ok := requests.Validate(c, &request, requests.UserPassengerSave); !ok {
		return
	}

	userPassengerModel := user_passenger.UserPassenger{
		UserID: auth.CurrentIntUID(c),
		Name:   request.Name,
		Phone:  request.Phone,
	}
	userPassengerModel.Create()
	if userPassengerModel.ID > 0 {
		response.Created(c, userPassengerModel)
	} else {
		response.Abort500(c, "创建失败，请稍后尝试~")
	}
}

func (ctrl *UserPassengersController) Update(c *gin.Context) {

	userPassengerModel := user_passenger.Get(c.Param("id"))
	if userPassengerModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyUserPassenger(c, userPassengerModel); !ok {
		response.Abort403(c)
		return
	}

	request := requests.UserPassengerRequest{}
	if ok := requests.Validate(c, &request, requests.UserPassengerSave); !ok {
		return
	}

	userPassengerModel.Name = request.Name
	userPassengerModel.Phone = request.Phone
	rowsAffected := userPassengerModel.Save()
	if rowsAffected > 0 {
		response.Data(c, userPassengerModel)
	} else {
		response.Abort500(c, "更新失败，请稍后尝试~")
	}
}

func (ctrl *UserPassengersController) Delete(c *gin.Context) {

	userPassengerModel := user_passenger.Get(c.Param("id"))
	if userPassengerModel.ID == 0 {
		response.Abort404(c)
		return
	}

	if ok := policies.CanModifyUserPassenger(c, userPassengerModel); !ok {
		response.Abort403(c)
		return
	}

	rowsAffected := userPassengerModel.Delete()
	if rowsAffected > 0 {
		response.Success(c)
		return
	}

	response.Abort500(c, "删除失败，请稍后尝试~")
}
